import { widgetManager } from '@/common/managers';
import { NMTopoBaseCommand } from '@/common/types';
import { nmAppErrorLog, nmAppLog } from '@/common/utils';
import i18n from '@/common/utils/i18next';
import { mesh } from '@/domain';
import { MessageTip } from '@amcax/base';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, KEYBOARD_KEY } from 'nextcae-base';
import { useEffect, useState } from 'react';
import { schema, uiSchema } from './data';
import { TopoDialogProps } from './type';

// 删除网格
function EraseMeshDialog({ title, onClose }: TopoDialogProps) {
  const [hintMessage] = useState('进入清除网格命令,请选择网格');
  const [formData, setFormData] = useState<any>({
    Selection: { source: [] },
  });
  useEffect(() => {
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keyup', onKeyUp);
    };
  }, []);
  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);
  const onKeyUp = (e: KeyboardEvent) => {
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };

  const handleSubmit = async (data) => {
    nmAppLog('handleSubmit====>:', data);
    if (data.Selection.source.length === 0) {
      return MessageTip.warning('请拾取Source网格！');
    }
    if (data) {
      try {
        const rspData = await mesh.delete(data.Selection.source);
        if (rspData?.failed?.length > 0) {
          // 提示删除失败的id列表
          MessageTip.warning(
            `删除失败的网格id列表：${rspData.failed.join(',')}`,
          );
        }
        setFormData({ Selection: { source: [] } });
      } catch (error) {
        nmAppErrorLog('mesh-delete-error:', error);
      }
      nmAppLog('handleSubmit:', data);
    }
  };

  const handleResultSelectChange = (data: IChangeEvent, id) => {
    nmAppLog('handleResultSelectChange:', data, id);
    if (data.formData) {
      if (id === 'root_MeshSettings_elementType') {
        setFormData({
          ...data.formData,
          MeshSettings: {
            ...data.formData.MeshSettings,
            method: '',
          },
        });
      } else {
        setFormData(data.formData);
      }
    }
  };
  const isFormDataValid = () => {
    return formData.Selection.source.length > 0;
  };
  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={'commands/mesh/remove-mesh'}
      onSubmit={handleSubmit}
      isFormDataValid={isFormDataValid()}
      onChange={handleResultSelectChange}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}></CmdDialogForm>
  );
}
// EraseMesh 清除网格
export const cmdEraseMesh: NMTopoBaseCommand = {
  id: 'cmdEraseMesh',
  icon: 'commands/mesh/erase-mesh',
  label: 'command.mesh.eraseMesh',
  create: (label: string, onClose: () => void, props) => (
    <EraseMeshDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
